package org.example.cloud.cosumer.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.cloud.cosumer.service.CosumerService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.Random;

/**
 * @Auther:Liu
 * @Testname:CosumerServiceImpl
 * @Date:2025/9/8 15:36
 */
@Slf4j
@Service
public class CosumerServiceImpl implements CosumerService {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @Override
    public String a() {
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-service-goverance-prodiver");
        log.info("获取到对象为: {}", instances);
        ServiceInstance serviceInstance = instances.get(0);
        log.info("其中数据为: {}", serviceInstance);
        String url = serviceInstance.getUri().toString();
        log.info("对象根路径为: {}", url);
        String forObject = restTemplate.getForObject(url + "/prodiver", String.class);
        return forObject;
    }

    @Override
    public String aradom() {
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-service-goverance-prodiver");
        log.info("获取到对象为: {}", instances);
        int i=(int)(Math.random()*instances.size());
        ServiceInstance serviceInstance = instances.get(i);
        log.info("其中数据为: {}", serviceInstance);
        String url = serviceInstance.getUri().toString();
        log.info("对象根路径为: {}", url);
        String forObject = restTemplate.getForObject(url + "/prodiver", String.class);
        return forObject;
    }
    int j=0;
    @Override
    public String abalance() {
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-service-goverance-prodiver");
        log.info("获取到对象为: {}", instances);
        ServiceInstance serviceInstance = instances.get(j);
        if (j==instances.size()-1){
            j=0;
        }else {
            j++;
        }
        log.info("其中数据为: {}", serviceInstance);
        String url = serviceInstance.getUri().toString();
        log.info("对象根路径为: {}", url);
        String forObject = restTemplate.getForObject(url + "/prodiver", String.class);
        return forObject;
    }
}
